package com.activemq.demo;


import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import lombok.extern.slf4j.Slf4j;

/**
 * Messages are redelivered to a client when any of the following occurs:
 * 1 A transacted session is used and rollback() is called.
 * 2 A transacted session is closed before commit() is called.
 * 3 A session is using CLIENT_ACKNOWLEDGE and Session.recover() is called.
 * 4 A client connection times out (perhaps the code being executed takes longer than the configured time-out period).
 */

@Slf4j
@Service
public class MqProducer {

    @Autowired
    private JmsTemplate jmsTemplate;

    public static final int PERSISTANT_MODE = 2;

    /**
     * 发送字符串的方式
     *
     * @param destinationName 目的地址
     * @param body            消息体内容字符串
     */
    public void sendMessage(String destinationName, String body) {

        log.info(((ActiveMQConnectionFactory)jmsTemplate.getConnectionFactory()).getRedeliveryPolicy().getMaximumRedeliveries()+"");

        Destination destination = new ActiveMQQueue(destinationName);

        jmsTemplate.setDeliveryMode(PERSISTANT_MODE);
        jmsTemplate.setSessionTransacted(true);
        //jmsTemplate.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);

        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(body);
            }
        });
    }

}
